<?php
/*
 * @Author: your name
 * @Date: 2022-02-25 17:10:26
 * @LastEditTime: 2022-03-10 20:45:39
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: /laravel_wuye/swoole_server/Function.php
 */
function mkdir_2($path,$pathError = []){
    if (!is_dir($path)) {
        $prePath = dirname($path).'/';
        if(is_dir( $prePath)){
            mkdir($path,0777);
            if(count($pathError) > 0){
                for($i=count($pathError)-1;$i>=0;$i--){
                    mkdir($pathError[$i],0777);
                }  
            } 
        }else{
            $pathError[] =$path;
            mkdir_2($prePath,$pathError);
        }
    }
}

function swooleWriteLogFunc($data ){
    $response = is_array($data['response']) ? $data['response'] : json_decode($data['response'], 1);
    $request = $data['request'];    //传入的参数
    co::create(function() use ( $request, $response){
        Swoole\Coroutine\System::sleep(0.2);
        
      
       if(!isset($response['error']) && isset($response['code'])  && $response['code'] != 404 ){  // 不等于404并且是不出错的情况下写入
        $Ymd =      date('Ymd');
        if( $response['code'] == 200 ||  $response['code'] == 100 || $response['code'] == -1 ){
            $dir = __ROOT__ . '/swoole_log/swoole_request/success/';   //访问成功日志
        }else{
            $dir = __ROOT__ . '/swoole_log/swoole_request/error/';    //访问错误日志
        }
        $logPath = $dir . $Ymd . '.log';
        mkdir_2($dir);
        if (!is_file($logPath)) {                                      //没有文件则把一个星期前的日志清除
            $scandir = scandir($dir);                                //获取文件夹所有文件
            $compare =  date('Y-m-d', strtotime($Ymd . ' -1 week'));  //把一个星期前的日志删除
            for ($i = 0; $i < count($scandir); $i++) {
                if ($scandir[$i] != "." &&  $scandir[$i] != "..") {
                    list($fileName, $type) = explode('.', $scandir[$i]);
                    if (strtotime($compare) > strtotime($fileName)) {
                        unlink($dir.$fileName . '.' . $type);    //删除文件
                    }
                }
            }
        }
        file_put_contents($logPath, json_encode([
            'date' => date('Y-m-d H:i:s'),
            'request' => $request,
            'response' => $response
        ], JSON_UNESCAPED_UNICODE) . PHP_EOL,FILE_APPEND); //访问日志



       }
    });     
}
